import path from 'path';
import { ServerConfig } from '../types/agent';

// 默认配置
const defaultConfig = {
  port: 3001,
  host: '0.0.0.0',
  dataDir: path.join(process.cwd(), 'data'),
  logsDir: path.join(process.cwd(), 'logs'),
  cors: {
    origin: ['http://localhost:3000', 'http://localhost:5173'],
    credentials: true
  },
  rateLimit: {
    windowMs: 15 * 60 * 1000, // 15分钟
    max: 100 // 限制每个IP 15分钟内最多100个请求
  },
  upload: {
    maxFileSize: 10 * 1024 * 1024, // 10MB
    allowedTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
  }
};

// 环境特定配置
const environmentConfigs = {
  development: {
    ...defaultConfig,
    cors: {
      ...defaultConfig.cors,
      origin: [...defaultConfig.cors.origin, 'http://localhost:8080']
    }
  },
  production: {
    ...defaultConfig,
    port: parseInt(process.env.PORT || '3001', 10),
    cors: {
      ...defaultConfig.cors,
      origin: process.env.ALLOWED_ORIGINS?.split(',') || defaultConfig.cors.origin
    }
  },
  test: {
    ...defaultConfig,
    port: 0, // 随机端口用于测试
    cors: {
      ...defaultConfig.cors,
      origin: ['http://localhost:3000']
    }
  }
};

// 获取环境
function getEnvironment() {
  return process.env.NODE_ENV || 'development';
}

/**
 * 获取当前环境的配置
 */
function getConfig(): any {
  const env = getEnvironment();
  const envConfig = environmentConfigs[env as keyof typeof environmentConfigs] || environmentConfigs.development;
  
  return {
    ...envConfig,
    // 环境变量覆盖
    port: parseInt(process.env.PORT || envConfig.port.toString(), 10),
    dataDir: process.env.DATA_DIR || envConfig.dataDir,
    logsDir: process.env.LOGS_DIR || envConfig.logsDir
  };
}

/**
 * 检查是否为开发环境
 */
export function isDevelopment(): boolean {
  return getEnvironment() === 'development';
}

/**
 * 检查是否为生产环境
 */
export function isProduction(): boolean {
  return getEnvironment() === 'production';
}

/**
 * 检查是否为测试环境
 */
export function isTest(): boolean {
  return getEnvironment() === 'test';
}

// 路径常量
export const PATHS = {
  DATA: path.join(process.cwd(), 'data'),
  BACKUP: path.join(process.cwd(), 'data', 'backups'),
  LOGS: path.join(process.cwd(), 'logs'),
  UPLOADS: path.join(process.cwd(), 'uploads')
};

// 配置验证
export function validateConfig(config: any): boolean {
  return (
    typeof config.port === 'number' &&
    config.port > 0 &&
    config.port < 65536 &&
    typeof config.dataDir === 'string' &&
    typeof config.logsDir === 'string'
  );
}

export { getConfig };

// 导出配置
export const config = getConfig();

// 打印配置信息（开发环境）
if (isDevelopment()) {
  console.log('Server Configuration:', {
    ...config,
    // 不打印敏感信息
  });
}